package org.yar.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.simpleini.Ini;

import android.content.Context;

public class Preferences extends Ini {
	private static final String FILENAME = "prefs.ini";
	private static final String FILE_SECTION = "FILES";
	
	private Context context;
	
	public Preferences(Context context) {
		super();
		
		this.context = context;
		try {
			this.loadFrom(context.openFileInput(FILENAME));
		} catch (IOException ie)
		{
			
		}
	}
	
	public void save()
	{
		try {
			this.saveTo(context.openFileOutput(FILENAME, Context.MODE_PRIVATE));
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
	}
	
	public Map<String, String> getFileSection()
	{
		return getSection(FILE_SECTION);
	}
	
	public List<File> getFiles()
	{
		List<File> list = new ArrayList<File>();
		for (String key: getFileSection().keySet())
		{
			if (!key.startsWith("FILE"))
			{
				continue;
			}
			
			File file = new File(getFileSection().get(key));
			if (!file.exists())
			{
				continue;
			}
			list.add(file);
		}
		
		return list;
	}
	
	public Ini addFile(File f)
	{
		
		try {
			int numFiles = getFileSection().size();
			
			for (File file: getFiles())
			{
				if (file.getCanonicalPath().equals(f.getCanonicalPath()))
				{
					return this;
				}
			}
			
			getFileSection().put(String.format("FILE%d", numFiles), f.getCanonicalPath());
		} catch (IOException e) {
		}
		return this;
	}
	
	public Ini removeFile(File f)
	{
		try {
			removeSection(f.getCanonicalPath());
			//getFileSection().remove(f.get)
			String key = null;
			for (Map.Entry<String, String> entry: getFileSection().entrySet())
			{
				if (entry.getValue().equals(f.getCanonicalPath()))
				{
					key = entry.getKey();
					break;
				}
			}
			if (key != null)
			{
				getFileSection().remove(key);
			}
		} catch (IOException e) {
			
		}
		return this;
		
	}
	
}
